import string
import time
import random

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from commodity.models import CommodityInfos
from shopper.form import LoginForm, LoginModelForm
from shopper.models import OrderInfos, CartInfos
from shopper.pays import get_pay


# Create your views here.

@login_required(login_url='shopper/login.html')
def shopperView(request):
    title = "个人中心"
    classContent = 'informations'
    t = request.GET.get('t', '')
    p = request.GET.get('p', 1)
    payTime = request.session.get('payTime', '')
    if t and payTime and t == payTime:
        payInfo = request.session.get('payInfo', '')
        OrderInfos.objects.create(**payInfo)
        del request.session['payInfo']
        del request.session['payTime']
    orderInfos = OrderInfos.objects.filter(user_id=request.user.id).order_by('-created')
    # 分页
    paginator = Paginator(orderInfos, 7)
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'shopper.html', locals())

def  loginView(request):
    title = "用户登录"
    classContent = "logins"
    if request.method == "POST":
        infos = LoginModelForm(data= request.POST)
        data = infos.data
        username = data['username']
        password = data['password']
        if User.objects.filter(username=username):
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return redirect(reverse('shopper:shopper'))
        else:
            state = "注册成功"
            d = dict(username=username, password=password, is_staff=1, is_active=1)
            user = User.objects.create_user(**d)
            user.save()
    else:
        infos = LoginModelForm()
    return render(request, 'login.html', locals())
def logoutView(request):
    logout(request)
    return redirect(reverse('index:index'))

@login_required(login_url='shopper/login.html')
def shopcartView(request):
    title = "我的购物车"
    classContent = "shopcarts"
    userId = request.user.id
    id = request.GET.get('id', "")
    quantity = request.GET.get('quantity', 1)
    if id:
        CartInfos.objects.update_or_create(
            commodityInfos_id=id,
            user_id=userId,
            defaults={'quantity': quantity}
        )
        return redirect('shopper:shopcart')
    getUserId = CartInfos.objects.filter(user_id=userId)
    commodityDict = {x.commodityInfos_id : x.quantity for x in getUserId}
    commodityInfos = CommodityInfos.objects.filter(id__in=commodityDict.keys())
    return render(request, 'shopcart.html', locals())

def deleteAPI(request):
    result = {'state': 'success'}
    userId = request.GET.get('userId', '')
    commodityId = request.GET.get('commodityId', '')
    if userId:
        CartInfos.objects.filter(user_id=userId).delete()
    elif commodityId:
        CartInfos.objects.filter(commodityInfos_id=commodityId).delete()
    else:
        result= {'state': 'fail'}
    return JsonResponse(result)

def paysView(request):
    total = request.GET.get('total', 0)
    total = total.replace('￥', '')
    try:
        total = float(total)
    except ValueError:
        return redirect('shopper:shopcart')
    if total > 0:
        timestamp = int(time.time() * 1000)
        random_str = "".join(random.choices(string.digits, k=6))
        out_trade_no = f"{timestamp}{random_str}"
        total_amount = "{:.2f}".format(total)
        payInfo = dict(price=total, user_id=request.user.id, state="已支付")
        request.session['payInfo'] = payInfo
        request.session['payTime'] = out_trade_no
        domain = 'http://' + request.get_host()
        return_url = f"{domain}/shopper/pay_callback/"
        print(f"out_trade_no: {out_trade_no}, type: {type(out_trade_no)}")
        print(f"total_amount: {total_amount},type: {type(total_amount)}")
        print(f"return_url: {return_url}, type: {type(return_url)}" )
        url = get_pay(out_trade_no, total_amount, return_url)
        print("支付宝支付链接:", url)
        if url:
            return redirect(url)
        else:
            return redirect('shopper:shopcart')
    else:
        return redirect('shopper:shopcart')

def payCallbackView(request):
    payTime = request.session.get('payTime','')
    if payTime:
        payInfo = request.session.get('payInfo','')
        if payInfo:
            OrderInfos.objects.create(**payInfo)
            del request.session['payInfo']
            del request.session['payTime']
    return redirect(reverse('shopper:shopper'))